
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.InetAddress;
import java.net.SocketPermission;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.*;

public class PlayerGUI extends JFrame {

	private static DefaultListModel listModel;
	private static DefaultListModel peerListModel;
	private String[] radioStations = {};
	private RadioPeer peer = null;
	private int port;
	private int capacity;
	
	public String src1;
	public String src2;
	
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {PlayerGUI pg = new PlayerGUI();
			pg.initUI();	
			pg.setVisible(true);
			}
		});
	}

	public PlayerGUI() {
		int randomPort = (1000+new Random().nextInt(9000));
		if((randomPort)%2 > 0){
			randomPort +=1;
		}
		
		port = randomPort;
		capacity = new Random().nextInt(4)+1;
		setTitle("" + port + " - " + capacity);
		setSize(300, 150);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		startJXSE();
	}

	public void startJXSE() {
		String name = "peer" + new Random().nextInt();
		CapacityModule capacityModule = new CapacityModule(capacity);
		peer = new RadioPeer(name,port,capacityModule);
	}

	public void initUI() {
		final JPanel panel = new JPanel(new BorderLayout());	
		final JButton newButton = new JButton("New");
		final JButton joinButton = new JButton("Join");
		final JButton startStreaming = new JButton("Start Stream");
		final JButton startListening = new JButton("Listen");
		final JButton getChildren = new JButton("get children");
		final JButton parent = new JButton("get parent");
		final TextField fileTextField = new TextField("file:///01_Intro.wav");
		final JLabel peerListLabel = new JLabel("My neighbours:");
		
		listModel = new DefaultListModel();
		final JList radioList = new JList(listModel);
		peerListModel = new DefaultListModel();
		final JList peerList = new JList(peerListModel);

		newButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				NewRadioDialog nrd = new NewRadioDialog(peer,port);
				nrd.setVisible(true);				
			}
		});

		joinButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JoinRadioFrame nrd = new JoinRadioFrame(peer);
				nrd.setVisible(true);	
				try {
					int port1 = port +2;
					int port2 = port +4;
					src1 = "rtp://"+InetAddress.getLocalHost().getHostAddress()+":"+port1+"/audio";
					src2 = "rtp://"+InetAddress.getLocalHost().getHostAddress()+":"+port2+"/audio";
					fileTextField.setText("rtp://"+InetAddress.getLocalHost().getHostAddress()+":"+port+"/audio");
				} catch (UnknownHostException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});

		getChildren.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(peer != null) {
					peer.popChildren();
				}

			}
		});
		parent.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(peer != null) {
					peer.popParent();
				}

			}
		});
		startStreaming.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				if(fileTextField.getText().startsWith("file")){
					RTPServer.startStream( fileTextField.getText(), fileTextField.getText(),peer.getChildren() , true);
				}
				else{
					RTPServer.startStream( src1, src2,peer.getChildren() , true);
				}
			}
		});
		
		startListening.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				String ip = "";
				try {
					ip = InetAddress.getLocalHost().getHostAddress();
				} catch (UnknownHostException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				port +=4;
				String url = "rtp://"+ip+":"+port+"/audio/";
				System.out.println(url);
				RTPClient.startStream(url);
			}
		});
		
		JPanel leftPanel = new JPanel();
		leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS));
		
		JPanel rightPanel = new JPanel(new BorderLayout());
		rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.PAGE_AXIS));
		
		JPanel centerPanel = new JPanel(new BorderLayout());
		centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS));
		
		panel.add(radioList, BorderLayout.NORTH);
		panel.add(leftPanel, BorderLayout.WEST);
		panel.add(fileTextField, BorderLayout.SOUTH);
		panel.add(rightPanel, BorderLayout.EAST);
		panel.add(centerPanel, BorderLayout.CENTER);
		
		
		leftPanel.add(new JLabel("Broadcast"));
		leftPanel.add(newButton);
		leftPanel.add(startStreaming);
		
		
		centerPanel.add(new JLabel("Tree structure"));
		centerPanel.add(parent);
		centerPanel.add(getChildren);
		
		rightPanel.add(new JLabel("Listen"));
		rightPanel.add(joinButton);
		rightPanel.add(startListening);
		
		
		
		
		
		
		
		//panel.add(peerListLabel);
		//panel.add(peerList);
		add(panel);

		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				peer.stop();
				System.exit(0);
			}
		});

	}

	public static void addRadioStation(String name, String hostAddress, String port) {
		listModel.addElement("tcp://" + hostAddress + ":" + port);
	}

	public static void removeRadioStation(String name) {

	}

	public static void addPeer(String id) {
		peerListModel.addElement(id);
	}

	public static void removeAll(String name) {
		peerListModel.removeAllElements();
	}

}


class NewRadioDialog extends JFrame {

	private Thread t;
	private int port;
	private RadioPeer peer;

	public NewRadioDialog(RadioPeer peer, int port) {
		t = new Thread(peer);
		this.port = port;
		this.peer = peer;
		initUI();
	}

	public void initUI() {				
		setLayout(new FlowLayout(10, 10, 10));

		final JTextField inputField = new JTextField(100);
		final JButton createButton = new JButton("Create");
		final JButton cancelButton = new JButton("Cancel");
		final JLabel textLabel = new JLabel("Station name : ");

		createButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String radioName = inputField.getText();
				String hostAddress = getHostAddress();
				if (radioName.length() > 0) {
					PlayerGUI.addRadioStation(radioName, hostAddress, port+"");
					peer.setMyAddress(getHostAddress());
					t.start();
					dispose();
				}
			}
		});

		cancelButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});

		add(textLabel);
		add(inputField);
		add(createButton);
		add(cancelButton);

		//setModalityType(ModalityType.APPLICATION_MODAL);

		setTitle("Create new station");
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setLocationRelativeTo(null);
		setSize(300, 150);

	}

	public String getHostAddress() {
		String hostAddress = "";
		try {
			hostAddress = InetAddress.getLocalHost().getHostAddress();		
		} catch (UnknownHostException e) {}
		return hostAddress;
	}

	public String getHostName() {
		String hostName = "";
		try {
			InetAddress addr = InetAddress.getLocalHost();
			hostName = addr.getHostName();			
		} catch (UnknownHostException e) {}
		return hostName;		
	}

	public String getIp() {
		String ip = "";
		try {
			InetAddress addr = InetAddress.getLocalHost();
			ip = addr.getHostAddress();

		} catch (UnknownHostException e) {}
		return ip;		
	}
}

class JoinRadioFrame extends JFrame {

	private Thread t;
	private RadioPeer peer;

	public JoinRadioFrame(RadioPeer peer) {
		t = new Thread(peer);
		this.peer=peer;
		initUI();
	}

	public void initUI() {				
		setLayout(new FlowLayout(10, 10, 10));

		final JTextField inputField = new JTextField(100);
		final JButton joinButton = new JButton("Join");
		final JButton cancelButton = new JButton("Cancel");
		final JLabel textLabel = new JLabel("Station to join : ");

		joinButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String radioName = inputField.getText();
				if (radioName.length() > 0) {
					PlayerGUI.addRadioStation(radioName, "","");
					peer.setRootAddress(radioName);
					peer.setMyAddress(getHostAddress());
					t.start();
					dispose();
				}
			}
		});

		cancelButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});

		add(textLabel);
		add(inputField);
		add(joinButton);
		add(cancelButton);

		//setModalityType(ModalityType.APPLICATION_MODAL);

		setTitle("Join an already existing station");
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setLocationRelativeTo(null);
		setSize(300, 150);

	}

	public String getHostAddress() {
		String hostAddress = "";
		try {
			hostAddress = InetAddress.getLocalHost().getHostAddress();		
		} catch (UnknownHostException e) {}
		return hostAddress;
	}

}
